python替换操作(replace,re.sub) | 您所在的位置:网站首页 › chiara provasi怎么读 › python替换操作(replace,re.sub) |
python替换的几种操作:
主要replace(),re.sub(),以及split()切片替换 一:简单的某个字符替换:replace()函数 str.replace(old, new, num) Python replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换 num 次。 eg: str = 'hello world!! ' print(str.replace('!',',',1)) print(str.replace('!',','))结果: 二:使用切片split()和join实现这个在上篇 第六点里面也写过 str = 'hello world!! ' new = '_hi' new_str = str.split('!') print(new.join(new_str)) 三:正则替换re.sub(pattern,repl,string,conut=0,flags=0) 参数:pattern正则表达式,repl要替换内容,string包含被替换内容的字符串,count查找替换的次数,返回一个string 如果没有找到匹配的,返回原字符串 import re str = 'hello world!! ' print(re.sub(r'[!]','_',str))结果 例如Windows系统上创建的txt文档名字不能包含特殊的字符 \ / : * ? " < > | 我们可以 def setFileTitle(self,filename): fileName = re.sub(r'[\/:*?"|]','-',filename)#去掉非法字符 self.file = open(fileName + ".txt","w+") |
CopyRight 2018-2019 实验室设备网 版权所有 |